package com.kingmed.kmss.bpmn.flow.listener;

import cn.hutool.core.collection.CollUtil;
import com.kingmed.kmss.bpmn.flow.service.custom.ProcessStatusSyncServiceImpl;
import com.kingmed.kmss.common.constant.bpmn.BpmnConstant;
import com.kingmed.kmss.common.constant.common.OperatorConstants;
import com.kingmed.kmss.common.exception.bpmn.ProcessNoAuditUserException;
import com.kingmed.kmss.common.utils.AppContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.flowable.identitylink.api.IdentityLink;
import org.flowable.task.service.delegate.DelegateTask;

import java.util.List;
import java.util.Set;

/**
 * 任务监听器 - 直接使用角色对应用户做为审批者，不需要通过组织找对应（这里主要是用来保存审批跟踪数据）
 *
 * @author wzg
 */
@Slf4j
public class DirectAssignUserTaskListener extends AssignUserTaskListener {

    /**
     *
     */
    private static final long serialVersionUID = -692867834396211555L;

    protected ProcessStatusSyncServiceImpl procStatusSvc = AppContextUtil.getBean(ProcessStatusSyncServiceImpl.class);


    @Override
    protected List<String> getBusinessAssignee(DelegateTask delegateTask) {
        Set<IdentityLink> candidates = delegateTask.getCandidates();
        String groupId = "";
        if (candidates != null && !candidates.isEmpty()) {
            groupId = candidates.iterator().next().getGroupId();
        }

        Integer orgType = (Integer) delegateTask.getVariable(BpmnConstant.VarKeys.ORG_TYPE);
        Long parentOrgId = (Long) delegateTask.getVariable(BpmnConstant.VarKeys.PARENT_ORG_ID);
        String taskName = delegateTask.getName();

        log.info("读取审批角色信息: " + groupId);
        // 根据审批角色直接查找审批人员
        List<String> candidateUsers = adminRemoteSvc.getRoleUsers(groupId, orgType, String.valueOf(parentOrgId));
        log.info("角色全部用户: " + candidateUsers);

        if (CollUtil.isEmpty(candidateUsers)) {
            String msg = String.format("无法找到下一个审批任务处理人, 审批角色: %s", taskName);
            log.error(msg);
            throw new ProcessNoAuditUserException(msg);
        }
        delegateTask.setAssignee(StringUtils.join(candidateUsers.toArray(),
                OperatorConstants.A_SEMICOLON_KEY) + OperatorConstants.A_SEMICOLON_KEY);
        return candidateUsers;
    }

}
